package com.cqhz.quwan.ui.activity

import android.content.Intent
import android.graphics.Color
import android.support.v7.widget.GridLayoutManager
import android.support.v7.widget.RecyclerView
import android.text.Editable
import android.text.TextWatcher
import com.blankj.utilcode.util.ConvertUtils.dp2px
import com.blankj.utilcode.util.KeyboardUtils
import com.blankj.utilcode.util.StringUtils.isEmpty
import com.cqhz.quwan.APP
import com.cqhz.quwan.ActivityInject
import com.cqhz.quwan.R
import com.cqhz.quwan.common.KeyContract
import com.cqhz.quwan.model.ExpertDetailBean
import com.cqhz.quwan.model.OrderBetInfoBean
import com.cqhz.quwan.model.OrderInfoBean
import com.cqhz.quwan.mvp.PlanDetailContract
import com.cqhz.quwan.mvp.PlanDetailPresenter
import com.cqhz.quwan.ui.base.GoBackActivity
import com.cqhz.quwan.ui.login.LoginActivity
import com.cqhz.quwan.ui.widget.GridSpacingItemDecoration
import com.cqhz.quwan.util.*
import com.google.gson.Gson
import com.google.gson.reflect.TypeToken
import kotlinx.android.synthetic.main.activity_plan_detail.*
import me.militch.quickcore.core.HasDaggerInject
import java.util.*
import javax.inject.Inject


/**
 * 方案详情
 * Created by Guojing on 2018/11/29.
 */
class PlanDetailActivity : GoBackActivity(), PlanDetailContract.View, HasDaggerInject<ActivityInject> {

    @Inject
    lateinit var planDetailPresenter: PlanDetailPresenter
    private var expertDetailBean: ExpertDetailBean? = null
    private var followStatus = 0
    // 投注需要上传的参数
    private var betTimes: Int = 10// 投注倍数
    private var orderId = ""
    private var expertId = ""
    private var userId = ""

    override fun inject(t: ActivityInject?) {
        t?.inject(this)
    }

    override fun titleBarText(): String? {
        return "方案详情"
    }

    override fun layout(): Int {
        return R.layout.activity_plan_detail
    }

    override fun initView() {
        planDetailPresenter.attachView(this)

        if (APP.get()!!.loginInfo != null) {
            orderId = intent.getStringExtra(KeyContract.OrderId)
            userId = APP.get()!!.loginInfo!!.userId!!
            expertId = intent.getStringExtra(KeyContract.ExpertId)
            planDetailPresenter.getProgrammeDetail(orderId, expertId, userId)
        } else {
            finish()
            showToast("请登录再试")
        }
        setOnClick()
    }

    /**
     * 设置点击事件
     */
    private fun setOnClick() {
        action_goto_expert.setOnClickListener {
            if (APP.get()!!.loginInfo == null) {
                startActivity(Intent(this, LoginActivity::class.java))
                return@setOnClickListener
            }

            val intent = Intent(context(), ExpertDetailActivity::class.java)
            intent.putExtra(KeyContract.UserId, expertId)
            startActivity(intent)
        }
        action_follow.setOnClickListener {
            val expertId = intent.getStringExtra(KeyContract.ExpertId)
            var tempStatus = if (followStatus == 1) 0 else 1
            planDetailPresenter.updateFollowStatus(expertId, userId, tempStatus.toString())
        }
        action_minus.setOnClickListener {
            KeyboardUtils.hideSoftInput(this)
            if (betTimes > 1) {
                betTimes -= 1
                et_bunch_number.setText("$betTimes")
            }
            onDataChange()
        }
        action_add.setOnClickListener {
            KeyboardUtils.hideSoftInput(this)
            betTimes += 1
            et_bunch_number.setText("$betTimes")
            onDataChange()
        }
        action_commit.setOnClickListener {
            if (expertDetailBean!!.pushOrderDetailVO.betTimes > betTimes) {
                betTimes = expertDetailBean!!.pushOrderDetailVO.betTimes
                et_bunch_number.setText("$betTimes")
                onDataChange()
                showToast("最低" + betTimes + "倍起跟")
                return@setOnClickListener
            }
            planDetailPresenter.addFollowOrder(userId.toLong(), orderId.toLong(), betTimes)
        }
        et_bunch_number.addTextChangedListener(object : TextWatcher {
            override fun afterTextChanged(s: Editable?) {
            }

            override fun beforeTextChanged(s: CharSequence?, start: Int, count: Int, after: Int) {
            }

            override fun onTextChanged(s: CharSequence?, start: Int, before: Int, count: Int) {
                try {
                    var value = s?.toString()?.toInt() ?: 0
                    betTimes = s?.toString()?.toInt() ?: 0
                    if (value == 0) {
                        betTimes = expertDetailBean!!.pushOrderDetailVO.betTimes
                        et_bunch_number.setText("$betTimes")
                    }
                } catch (e: NumberFormatException) {
                    betTimes = expertDetailBean!!.pushOrderDetailVO.betTimes
                }

                onDataChange()
            }
        })
    }

    /**
     * 当选中状态改变时
     */
    private fun onDataChange() {
        var amountPay = multiply(expertDetailBean!!.pushOrderDetailVO.singleAmt.toDouble(), betTimes.toDouble())
        tv_total_number.text = "共 " + amountPay.toString().formatNoZero() + "趣豆"
    }

    /**
     * 初始化列表适配器
     */
    private fun initHitAdapter(list: List<String>) {
        // 当前页面列表的数据和适配器
        var adapter = CommonAdapterHelper.getHitListAdapter(list)
        // 当前页面列表适配器的事件
        rv_hit_list.layoutManager = GridLayoutManager(this, 7) as RecyclerView.LayoutManager?
        rv_hit_list.addItemDecoration(GridSpacingItemDecoration(7, dp2px(0f), false))
        rv_hit_list.isNestedScrollingEnabled = false// 让NestedScrollView滑动顺滑
        rv_hit_list.adapter = adapter
    }

    override fun setProgrammeDetail(bean: ExpertDetailBean) {
        expertDetailBean = bean
        followStatus = bean.followStatus

        iv_avatar.setLoadImage(this, bean.headUrl, R.drawable.default_head)
        val level = getDrawable(
                when (bean.rank) {
                    1 -> R.drawable.details_level_1
                    2 -> R.drawable.details_level_2
                    3 -> R.drawable.details_level_3
                    else -> R.drawable.details_level_1
                })
        level.setBounds(0, 0, level.minimumWidth, level.minimumHeight)
        tv_name.setCompoundDrawables(null, null, level, null)
        tv_name.text = bean.nick
        tv_desc.text = bean.introduce
        action_follow.text = if (followStatus == 1) "取消关注" else "关注"
        tv_week_orders.text = "发" + bean.createOrders + "中" + bean.hitNums
        tv_week_hits.text = bean.hitOdds.formatNoZero() + "%"
        tv_week_profits.text = bean.profitOdds.formatNoZero() + "%"
        if (!isEmpty(bean.lastStatus)) {
            val hits = ArrayList(bean.lastStatus.split(","))
            initHitAdapter(hits)
        }

        tv_play_type.text = bean.pushOrderDetailVO.betType
        tv_profit_rate.text = "佣金：" + bean.pushOrderDetailVO.commissionRate.formatNoZero() + "%"
        tv_sp.text = "SP：" + bean.pushOrderDetailVO.sp

        var moneyText = "跟单金额：" + bean.pushOrderDetailVO.followAmt + "趣豆"
        var numberText = "跟单人数：" + bean.pushOrderDetailVO.follows + "人"
        tv_follow_amount.text = displayTextColor(moneyText, bean.pushOrderDetailVO.followAmt.toString())
        tv_follow_number.text = displayTextColor(numberText, bean.pushOrderDetailVO.follows.toString())

        tv_plan_number.text = bean.pushOrderDetailVO.projectId
        tv_time.text = bean.pushOrderDetailVO.createTime.formatSystemTime("yyyy-MM-dd HH:mm")
        tv_deadline.text = bean.pushOrderDetailVO.closeTime.formatSystemTime("yyyy-MM-dd HH:mm")

        onDataChange()
    }

    override fun updateSuccess() {
        followStatus = if (followStatus == 1) 0 else 1
        action_follow.text = if (followStatus == 1) "取消关注" else "关注"
    }

    override fun commitSuccess(orderInfo: OrderInfoBean) {
        val orderBetInfoList = Gson().fromJson(orderInfo.orderBetJson, object : TypeToken<List<OrderBetInfoBean>>() {}
                .type) as? MutableList<OrderBetInfoBean>
        var playType = if (orderBetInfoList == null) {
            ""
        } else {
            when (orderBetInfoList!![0].playType) {
                1 -> "胜平负"
                2 -> "让球胜平负"
                3 -> "比分"
                4 -> "总进球数"
                5 -> "半全场"
                6 -> "混合投注"
                7 -> "单关固定"
                8 -> "猜一场"
                9 -> "2选1"
                else -> "其他"
            }
        }

        val intent = Intent(this, GoPaymentActivity::class.java)
        intent.putExtra(KeyContract.Amount, orderInfo!!.payAmount?.toDouble())
        intent.putExtra(KeyContract.ActualAmount, orderInfo!!.payAmount?.toDouble())
        intent.putExtra(KeyContract.OrderId, orderInfo!!.id)
        intent.putExtra(KeyContract.LotteryName, "竞猜足球 $playType")
        startActivity(intent)
    }

    override fun onResume() {
        super.onResume()
        planDetailPresenter.getProgrammeDetail(orderId, expertId, userId)
    }

    override fun onDestroy() {
        super.onDestroy()
        planDetailPresenter.detachView()
    }
}
